import {
  Table,
  Transfer,
  Space,
  Button,
  Modal,
  Form,
  Input,
  Upload,
} from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import difference from 'lodash/difference';
import { useState } from 'react';

const layout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
};

const tailLayout = {
  wrapperCol: {
    offset: 0,
    span: 16,
  },
};
const App = () => {
  const [form] = Form.useForm();
  // Customize Table Transfer

  const [mockData, setMockData] = useState(
    Array.from({
      length: 20,
    }).map((_, i) => ({
      key: i.toString(),
      title: {
        userimg: 'https://api.isoyu.com/mm_images.ph',
        username: i,
        userurl: 'https://www.baidu.com/',
      },
    })),
  );
  const originTargetKeys = mockData
    .filter((item) => Number(item.key) % 3 > 1)
    .map((item) => item.key);

  //选中的项，['2', '5', '8', '11', '14', '17']   key的一个字符串数组
  const [targetKeys, setTargetKeys] = useState(originTargetKeys);

  const [isModalVisible, setIsModalVisible] = useState(false);

  const [idCheck, setIsCheck] = useState();

  const remove = (val) => {
    setMockData(mockData.filter((item) => item !== val));
  };

  const leftTableColumns = [
    {
      dataIndex: 'title',
      title: '运营位图片',
      render: (index, record) => (
        <Space size="middle">
          <div style={{ display: 'flex' }}>
            <img
              src={index.userimg}
              width={100}
              height={100}
              style={{ marginRight: 20 }}
            />
            <div>
              <div>运营位名称：{index.username}</div>
              <a>落地链接：{index.userurl}</a>
            </div>
          </div>
        </Space>
      ),
    },
    {
      title: '操作',
      render: (index, record) => (
        <Space size="middle">
          <a onClick={() => update(record)}>修改</a>
          <a onClick={() => remove(record)}>删除</a>
        </Space>
      ),
    },
  ];

  //删除
  const removeValue = (val) => {
    let arr = targetKeys.filter((item) => item !== val.key);
    console.log(arr);
    setTargetKeys(arr);
  };
  //修改
  const update = (val) => {
    const {
      key,
      title: { userimg, username, userurl },
    } = val;
    form.setFieldsValue({
      userimg: [{ uid: key, key: userimg, url: userimg }],
      username,
      userurl,
    });

    setIsCheck(val);
    setIsModalVisible(true);

    console.log(val);
  };
  //上移
  const moveUp = (val) => {
    let arr = [...targetKeys];
    let idx = targetKeys.indexOf(val.key);
    let value = targetKeys[idx - 1];
    arr[idx] = value;
    arr[idx - 1] = val.key;
    setTargetKeys(arr);
  };
  //下移
  const moveDown = (val) => {
    let arr = [...targetKeys];
    let idx = targetKeys.indexOf(val.key);
    let value = targetKeys[idx + 1];
    arr[idx] = value;
    arr[idx + 1] = val.key;
    setTargetKeys(arr);
  };

  const rightTableColumns = [
    {
      title: '运营图片',
      dataIndex: 'title',
      render: (index, record) => (
        <Space size="middle">
          <div style={{ display: 'flex' }}>
            <img
              src={index.userimg}
              width={100}
              height={100}
              style={{ marginRight: 20 }}
            />
            <div>
              <div>运营位名称：{index.username}</div>
              <a>落地链接：{index.userurl}</a>
            </div>
          </div>
        </Space>
      ),
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space size="middle">
          {targetKeys.indexOf(record.key) === 0 ? (
            ''
          ) : (
            <a onClick={() => moveUp(record)}>上移</a>
          )}
          {targetKeys.indexOf(record.key) === targetKeys.length - 1 ? (
            ''
          ) : (
            <a onClick={() => moveDown(record)}>下移</a>
          )}
          <a onClick={() => update(record)}>修改</a>
          <a onClick={() => removeValue(record)}>删除</a>
        </Space>
      ),
    },
  ];

  const onChange = (nextTargetKeys) => {
    setTargetKeys(nextTargetKeys);
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = async () => {
    const { userimg, username, userurl } = await form.validateFields();
    // console.log(res);
    //判断是不是回填
    if (idCheck) {
      let arr = [...mockData];
      let idx = mockData.indexOf(idCheck);
      arr[idx] = {
        key: idCheck.key,
        title: {
          userimg: userimg[0].thumbUrl,
          username,
          userurl,
        },
      };
      setMockData(arr);
    } else {
      setMockData([
        ...mockData,
        {
          key: new Date(),
          title: {
            userimg: userimg[0].thumbUrl,
            username,
            userurl,
          },
        },
      ]);
    }

    setIsModalVisible(false);
    setIsStatus(false);
    form.resetFields();
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setIsStatus(false);
  };

  const [loading, setloading] = useState(false);
  const [isStatus, setIsStatus] = useState(false);

  const NormFile = (e) => {
    if (e.file.status === 'uploading') {
      setloading(true);
    } else {
      setloading(false);
    }
    if (e.fileList.length > 0) {
      setIsStatus(true);
    } else {
      setIsStatus(false);
    }
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const TableTransfer = ({ leftColumns, rightColumns, ...restProps }) => (
    <Transfer
      {...restProps}
      showSelectAll={false}
      selectAllLabels={[<div>未使用的</div>, <div>使用中的</div>]}
      titles={[
        <Button type="primary" onClick={showModal}>
          新增运营位
        </Button>,
      ]}
    >
      {({
        direction,
        filteredItems,
        onItemSelectAll,
        onItemSelect,
        selectedKeys: listSelectedKeys,
        disabled: listDisabled,
      }) => {
        const columns = direction === 'left' ? leftColumns : rightColumns;
        const rowSelection = {
          getCheckboxProps: (item) => ({
            disabled: listDisabled || item.disabled,
          }),

          onSelectAll(selected, selectedRows) {
            const treeSelectedKeys = selectedRows
              .filter((item) => !item.disabled)
              .map(({ key }) => key);
            const diffKeys = selected
              ? difference(treeSelectedKeys, listSelectedKeys)
              : difference(listSelectedKeys, treeSelectedKeys);
            onItemSelectAll(diffKeys, selected);
          },

          onSelect({ key }, selected) {
            onItemSelect(key, selected);
          },

          selectedRowKeys: listSelectedKeys,
        };
        return (
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={filteredItems}
            size="small"
            style={{
              pointerEvents: listDisabled ? 'none' : undefined,
            }}
            onRow={({ key, disabled: itemDisabled }) => ({
              onClick: () => {
                if (itemDisabled || listDisabled) return;
                onItemSelect(key, !listSelectedKeys.includes(key));
              },
            })}
          />
        );
      }}
    </Transfer>
  );

  return (
    <>
      {console.log(mockData, targetKeys)}
      <TableTransfer
        dataSource={mockData}
        targetKeys={targetKeys}
        onChange={onChange}
        filterOption={(inputValue, item) =>
          item.title.indexOf(inputValue) !== -1 ||
          item.tag.indexOf(inputValue) !== -1
        }
        leftColumns={leftTableColumns}
        rightColumns={rightTableColumns}
      />
      <Modal
        title={idCheck ? '修改' : '新增'}
        visible={isModalVisible}
        // onOk={handleOk}
        onCancel={handleCancel}
        // cancelText={'取消'}
        // okText={'确定'}
        footer={null}
      >
        <Form {...layout} form={form} name="control-hooks">
          <Form.Item
            name="userimg"
            label="运营位图片"
            rules={[{ required: true, message: 'Please input your username!' }]}
            valuePropName="fileList"
            getValueFromEvent={NormFile}
            extra="建议尺寸 1024*648， 格式限制 png, jpg, jpeg, jif, mp4"
          >
            <Upload
              name="multipartFile"
              action="/upload.do"
              listType="picture-card"
            >
              {isStatus ? '' : uploadButton}
            </Upload>
          </Form.Item>
          <Form.Item
            name="username"
            label="运营位名称"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item name="userurl" label="运营位链接">
            <Input placeholder="请输入" />
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button onClick={handleCancel} style={{ margin: '0 20px' }}>
              取消
            </Button>

            <Button type="primary" onClick={handleOk}>
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default App;
